home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 26 / Cream of the Crop 26.iso / program / ddj0897.zip / RCSC.ZIP / LIB86 / SPRINTF.C < prev   
C/C++ Source or Header  |  1997-01-12  |  2KB  |  55 lines

  1. #include "stdio.h"
  2. /*
  3. ** sprintf(buffer, ctlstring, arg, arg, ...) - Formatted print.
  4. ** Operates as described by Kernighan & Ritchie.
  5. ** b, c, d, o, s, u, and x specifications are supported.
  6. ** Note: b (binary) is a non-standard extension.
  7. */
  8. sprintf(argc) int argc; {
  9.   int *nxtarg;
  10.   int  arg, left, pad, cc, len, maxchr, width;
  11.   char *ctl, *sptr, str[17];
  12.   char *ptr;
  13.   cc = 0;                                         
  14.   nxtarg = CCARGC() + &argc - 1;
  15.   ptr = *nxtarg--;
  16.   ctl = *nxtarg--;                          
  17.   while(*ctl) {
  18.     if(*ctl!='%') {*ptr++ = *ctl++; ++cc; continue;}
  19.     else ++ctl;
  20.     if(*ctl=='%') {*ptr++ = *ctl++; ++cc; continue;}
  21.     if(*ctl=='-') {left = 1; ++ctl;} else left = 0;       
  22.     if(*ctl=='0') pad = '0'; else pad = ' ';           
  23.     if(isdigit(*ctl)) {
  24.       width = atoi(ctl++);
  25.       while(isdigit(*ctl)) ++ctl;
  26.       }
  27.     else width = 0;
  28.     if(*ctl=='.') {            
  29.       maxchr = atoi(++ctl);
  30.       while(isdigit(*ctl)) ++ctl;
  31.       }
  32.     else maxchr = 0;
  33.     arg = *nxtarg--;
  34.     sptr = str;
  35.     switch(*ctl++) {
  36.       case 'c': str[0] = arg; str[1] = NULL; break;
  37.       case 's': sptr = arg;        break;
  38.       case 'd': itoa(arg,str);     break;
  39.       case 'b': itoab(arg,str,2);  break;
  40.       case 'o': itoab(arg,str,8);  break;
  41.       case 'u': itoab(arg,str,10); break;
  42.       case 'x': itoab(arg,str,16); break;
  43.       default:  *ptr = 0; return (cc);
  44.       }
  45.     len = strlen(sptr);
  46.     if(maxchr && maxchr<len) len = maxchr;
  47.     if(width>len) width = width - len; else width = 0; 
  48.     if(!left) while(width--) {*ptr++ = pad; ++cc;}
  49.     while(len--) {*ptr++ = *sptr++; ++cc; }
  50.     if(left) while(width--) {*ptr++ = pad; ++cc;}  
  51.     }
  52.   *ptr = 0;
  53.   return(cc);
  54.   }
  55.